package hedron.db.model;

import hedron.Application;
import hedron.db.DBManager;
import java.sql.Connection;
import java.sql.ResultSet;

public class User extends AbstractModel {

	private long USER_ID = 0;
	private String U_FULLNAME = EMPTY_STR;
	private String U_NAME = EMPTY_STR;
	private String U_PASS = EMPTY_STR;
	private long U_ACCESS = 0;

	@Override
	public long getID() {
		return USER_ID;
	}

	@Override
	public String getIDName() {
		return "USER_ID";
	}

	@Override
	public String getTableName() {
		return "HUSER";
	}

	public User() {}

	public User(ResultSet rs) {
		if (rs == null) {
			throw new IllegalArgumentException("ResultSet might not be null");
		}
		if (!load(rs)) {
			throw new IllegalArgumentException("cannot load from ResultSet");
		}
	}

	@Override
	public boolean load(ResultSet rs) {
		DBManager db = Application.DB;
		USER_ID = db.getLong(rs, getIDName(), 0);
		if (USER_ID == 0) {
			return false;
		}
		U_FULLNAME = db.getString(rs, "STOCK_NAME");
		U_NAME = db.getString(rs, "STOCK_NAME");
		U_PASS = db.getString(rs, "STOCK_NAME");
		U_ACCESS = db.getLong(rs, "GROUP_ID");
		return true;
	}

	@Override
	public boolean isValid() {
		return isNotEmpty(U_NAME);
	}

	@Override
	public boolean store(Connection conn) {
		StringBuilder sql = new StringBuilder();

		if (getID() <= 0) {// insert
			USER_ID = Application.ID.getNewID();
			sql.append("insert into ");
			sql.append(getTableName());
			sql.append("(USER_ID, U_FULLNAME, U_NAME, U_PASS, U_ACCESS) values(?,?,?,?,?)");
			return db.ddlQuery(conn, sql.toString(), USER_ID, U_FULLNAME, U_NAME, U_PASS, U_ACCESS);
		} else {// update
			sql.append("update ");
			sql.append(getTableName());
			sql.append(" SET U_FULLNAME = ?, U_NAME = ?, U_PASS = ?, U_ACCESS = ?");
			sql.append(" where USER_ID = ").append(USER_ID);
			return db.ddlQuery(conn, sql.toString(), U_FULLNAME, U_NAME, U_PASS, U_ACCESS);
		}
	}

	@Override
	public boolean delete(Connection conn) {
		return false;
	}

}
